$(document).ready(function() {
	
	var lastSelType;
	var lastSelDetail;
	var arrType = new Array();
	var arrDetail = new Array();
	var cTypeId = 0;
	var cDetailId = 0 ;
	
	function compareCurToLastDataType(curSelData,lastSelData) {
	
		if(curSelData.codeName != lastSelData.codeName){
			return false;
		}
		
		return true;
	}
	
	function setUpdateType(grid,dataSet,lastSel) {
		
		var lastSelData = $("#"+grid).jqGrid("getRowData",lastSel);
			    	   					
			for (var i = 0; i < dataSet.length; i++) {
				if(lastSel == dataSet[i]["CID"] ){
					if( !compareCurToLastDataType(dataSet[i], lastSelData) ){
						if( dataSet[i].CRUD == "R" || dataSet[i].CRUD == "U"){
							dataSet[i].CRUD = "U";
							$("#"+grid).jqGrid("setCell",lastSel,"CRUD","U");
						}
					}					
				}
		}
	}
	function compareCurToLastDataDetail(curSelData,lastSelData) {
		
		if(curSelData.codeName != lastSelData.codeName || curSelData.sortOrder != lastSelData.sortOrder){
			return false;
		}
		
		return true;
	}
	
	function setUpdateDetail(grid,dataSet,lastSel) {
		
		var lastSelData = $("#"+grid).jqGrid("getRowData",lastSel);
		
		for (var i = 0; i < dataSet.length; i++) {
			if(lastSel == dataSet[i]["CID"] ){
				if( !compareCurToLastDataDetail(dataSet[i], lastSelData) ){
					if( dataSet[i].CRUD == "R" || dataSet[i].CRUD == "U"){
						dataSet[i].CRUD = "U";
						$("#"+grid).jqGrid("setCell",lastSel,"CRUD","U");
					}
				}					
			}
		}
	}
	
	function setEditable(grid,column,curSelData) {
		if( curSelData.CRUD == "C" ){
				$("#"+grid).jqGrid("setColProp",column, {editable:true});
				
			}else if( curSelData.CRUD == "R" || curSelData.CRUD == "U"){
				$("#"+grid).jqGrid("setColProp",column, {editable:false}); 
			}
	}
	
	function resetEditable(grid,column) {
		$("#"+grid).jqGrid("setColProp",column, {editable:true});
	}
	
	function arrayView(array,div){
		var arrTemp = new Array();
		
		for (var i = 0; i < array.length; i++) {
			var data = array[i];
			var arr = new Array();
			
			for ( var e in data) {
				arr.push(e+": "+data[e]);
			}
			
			arrTemp.push("{ "+arr.join(", ")+" }"+"<br>");
		}
		
		$("#"+div).html("[ "+arrTemp.join(",")+" ]");
	}
	
	$("#grid").jqGrid({
		pager: "#pager",
		caption : "분류코드",
	    height : "200",
	    rowNum : 10,
	    rowList : [10,20,30],
	    colNames : ["분류코드","분류코드명","CRUD","CID"],
		colModel : [
		            {name: "codeType", width : 100 , width: "400px" , editable: true},
		            {name: "codeName", width : 100, width: "400px", editable: true},
		            {name: "CRUD", width : 100},
		            {name: "CID", width : 100}
		           ],
	   editurl: "clientArray",
       onSelectRow : function(id){   
    	   		
    	   				//console.log("============== start: onSelectRow id="+id);
    	   
			    	    
    	   				var curSelRow =  $("#grid").jqGrid("getGridParam","selrow");
    	   				var curSelData = $("#grid").jqGrid("getRowData",curSelRow);
    	   				
    	   				if( id && id !== lastSelType){
    	   					jQuery('#grid').jqGrid('saveRow',lastSelType,false);
    	   					    	   					    	   					
    	   					setUpdateType("grid", arrType, lastSelType);
    	   					
    	   					lastSelType = id;
    	   				}
    	   				
    	   				$("#codeType").val(curSelData.codeType);
	   					$("#codeName").val(curSelData.codeName);
	   					
	   					setEditable("grid", "codeType",curSelData);
	   					
    	   				$("#grid").jqGrid("editRow",id);
    	   				
    	   				resetEditable("grid", "codeType");
    	   				
    	   				$.ajax({
    	   					url : "getCodeBookDetailList.do?codeType="+$("#codeType").val(),
    	   					dataType : "json",
    	   					type : "get",
    	   					success : function(data) {
    	   						
    	   						var rows = data.rows;
    	   						
    	   						arrDetail = new Array();
    	   						cDetailId = 0;
    	   						
    	   						$("#grid2").jqGrid("clearGridData");
    	   						
    	   						for (var i = 0, len = rows.length; i < len; i++) {
    	   							rows[i].CRUD = "R";
    	   							rows[i].CID = rows[i].codeDetail;
    	   							
    	   							arrDetail.push(rows[i]);
    	   							$("#grid2").jqGrid("addRowData",rows[i].codeDetail,rows[i]);
    	   						}
    	   						
    	   						arrayView(arrType,"test1");
    	   						arrayView(arrDetail,"test2");
    	   					}
    	   				});	
    
    	   				//console.log("============== end: onSelectRow id="+id);
    	       		}
			}).navGrid("#pager",{
			search : true,
			edit : true,
			add : true,
			del : true
			});
	
	$("#grid2").jqGrid({
		pager: "#pager2",
		caption : "상세코드",
	    height : "200",
	    rowNum : 10,
	    rowList : [10,20,30],
	    colNames : ["상세코드","상세코드명","정렬순서","CRUD","CID"],
		colModel : [
		            {name: "codeDetail", width : 100 , width: "200px", editable: true},
		            {name: "codeName", width : 100, width: "400px", editable: true},
		            {name: "sortOrder", width : 100, width: "200px", editable: true},
		            {name: "CRUD", width : 100},
		            {name: "CID", width : 100}
		           ],
	   editurl: "clientArray",
       onSelectRow : function(id){   
    	 //console.log("============== start: onSelectRow id="+id);
    	   
					var curSelRow =  $("#grid2").jqGrid("getGridParam","selrow");
					var curSelData = $("#grid2").jqGrid("getRowData",curSelRow);
					
					if( id && id !== lastSelDetail){
						jQuery('#grid2').jqGrid('saveRow',lastSelDetail,false);
												    	   					
						setUpdateDetail("grid2", arrDetail, lastSelDetail);
						
						lastSelDetail = id;
					}
					
					setEditable("grid2", "codeDetail",curSelData);
					
					$("#grid2").jqGrid("editRow",id);
					
					resetEditable("grid2", "codeDetail");
					
					arrayView(arrType,"test1");
					arrayView(arrDetail,"test2");
					
					//console.log("============== end: onSelectRow id="+id);
    	       		}
			}).navGrid("#pager2",{
			search : true,
			edit : true,
			add : true,
			del : true
			});
	
	$.ajax({
		url : "getCodeBookTypeList.do",
		dataType : "json",
		type : "get",
		success : function(data) {
			
			var rows = data.rows;
			
			for (var i = 0, len = rows.length; i < len; i++) {
				rows[i].CRUD = "R";
				rows[i].CID = rows[i].codeType;
				arrType.push(rows[i]);
				
				$("#grid").jqGrid("addRowData",rows[i].codeType,rows[i]);
			}
			
			$("#codeType").val(rows[0].codeType);
			$("#codeName").val(rows[0].codeName);
			
			arrayView(arrType,"test1");
			arrayView(arrDetail,"test2");
		}
	});	
	
	$.ajax({
		url : "getCodeBookDetailList.do",
		dataType : "json",
		type : "get",
		success : function(data) {
			
			var rows = data.rows;
			
			for (var i = 0, len = rows.length; i < len; i++) {
				rows[i].CRUD = "R";
				rows[i].CID = rows[i].codeDetail;
				arrDetail.push(rows[i]);
				
				$("#grid2").jqGrid("addRowData",rows[i].codeDetail,rows[i]);
			}
			
			arrayView(arrType,"test1");
			arrayView(arrDetail,"test2");
		}
	});	
	
	$("#search").click(function() {
		var searchCategory = $("#searchCategory").val();
		var searchData = $("#searchData").val();
		
		$("#grid").jqGrid("clearGridData");
		
		$.ajax({
			url : "getCodeBookTypeList.do?searchCategory="+searchCategory+"&searchData="+searchData,
			dataType : "json",
			type : "get",
			success : function(data) {
				
				var rows = data.rows;
				
				arrType = new Array();
				cTypeId = 0;
				
				for (var i = 0, len = rows.length; i < len; i++) {
					rows[i].CRUD = "R";
					rows[i].CID = rows[i].codeType;
					arrType.push(rows[i]);
					
					$("#grid").jqGrid("addRowData",rows[i].codeType,rows[i]);
				}
				
				arrayView(arrType,"test1");
				arrayView(arrDetail,"test2");
			}
		});
	});
	
	$("#insertType").click(function() {
		
		$("#grid").jqGrid("saveRow",lastSelType,false);
		$("#grid").jqGrid("addRowData",cTypeId,{CRUD: "C",CID: cTypeId},"first");
		$("#grid").jqGrid("editRow",cTypeId);
		
		arrType.push({ codeType: cTypeId, sortOrder: 0,CRUD: "C", CID: cTypeId});
		lastSelType = cTypeId++;
		
		$("#grid2").jqGrid("clearGridData");
		$("#codeType").val("");
		$("#codeName").val("");
		
		arrayView(arrType,"test1");
		arrayView(arrDetail,"test2");
		
	});
	
	$("#insertDetail").click(function() {
		
		if( $("#codeType").val() == "" || $("#codeName").val() == ""){
			alert("분류코드를 선택해주세요");
			
			return;
		}
		
		$("#grid2").jqGrid("saveRow",lastSelDetail,false);
		$("#grid2").jqGrid("addRowData",cDetailId,{CRUD: "C", CID: cDetailId },"first");
		$("#grid2").jqGrid("editRow",cDetailId);
		
		arrDetail.push({ codeType: $("#codeType").val(), codeDetail: cDetailId, CRUD: "C", CID: cDetailId});
		lastSelDetail = cDetailId++;
		
		arrayView(arrType,"test1");
		arrayView(arrDetail,"test2");
		
	});
	
	$("#deleteType").click(function() {
		
		var curSelRow =  $("#grid").jqGrid("getGridParam","selrow");
		var curSelData = $("#grid").jqGrid("getRowData",curSelRow);
				
		for (var i = 0; i < arrType.length; i++) {
			if( curSelRow == arrType[i].CID ){
				if( curSelData.CRUD == "C" ){
					arrType = arrType.filter(function(data) {
						return curSelRow != data.CID;
					});
					
				}else if( curSelData.CRUD == "R" || curSelData.CRUD == "U"){
					arrType[i].CRUD = "D";
				}
			}	
		}
		
		$("#grid").jqGrid("delRowData",curSelRow);
		$("#grid2").jqGrid("clearGridData");
		$("#codeType").val("");
		$("#codeName").val("");
		
		arrayView(arrType,"test1");
		arrayView(arrDetail,"test2");
	});
	
	$("#deleteDetail").click(function() {
		
		var curSelRow =  $("#grid2").jqGrid("getGridParam","selrow");
		var curSelData = $("#grid2").jqGrid("getRowData",curSelRow);
		
		for (var i = 0; i < arrDetail.length; i++) {
			if( curSelRow == arrDetail[i].CID ){
				if( curSelData.CRUD == "C" ){
					arrDetail = arrDetail.filter(function(data) {
						return curSelRow != data.CID;
					});
					
				}else if( curSelData.CRUD == "R" || curSelData.CRUD == "U"){
					arrDetail[i].CRUD = "D";
				}
			}	
		}
		
		$("#grid2").jqGrid("delRowData",curSelRow);
		
		arrayView(arrType,"test1");
		arrayView(arrDetail,"test2");
	});
	
	$("#cancelType").click(function() {
		var searchCategory = $("#searchCategory").val();
		var searchData = $("#searchData").val();
		
		$("#grid").jqGrid("clearGridData");
		
		$.ajax({
			url : "getCodeBookTypeList.do?searchCategory="+searchCategory+"&searchData="+searchData,
			dataType : "json",
			type : "get",
			success : function(data) {
				
				var rows = data.rows;
				
				arrType = new Array();
				cTypeId = 0;
				
				for (var i = 0, len = rows.length; i < len; i++) {
					rows[i].CRUD = "R";
					rows[i].CID = rows[i].codeType;
					arrType.push(rows[i]);
					
					$("#grid").jqGrid("addRowData",rows[i].codeType,rows[i]);
				}
				
				arrayView(arrType,"test1");
				arrayView(arrDetail,"test2");
			}
		});
	});
	
	$("#cancelDetail").click(function() {
		$.ajax({
				url : "getCodeBookDetailList.do?codeType="+$("#codeType").val(),
				dataType : "json",
				type : "get",
				success : function(data) {
					
					var rows = data.rows;
					
					arrDetail = new Array();
					cDetailId = 0;
					
					$("#grid2").jqGrid("clearGridData");
					
					for (var i = 0, len = rows.length; i < len; i++) {
						rows[i].CRUD = "R";
						rows[i].CID = rows[i].codeDetail;
						
						arrDetail.push(rows[i]);
						$("#grid2").jqGrid("addRowData",rows[i].codeDetail,rows[i]);
					}
					
					arrayView(arrType,"test1");
					arrayView(arrDetail,"test2");
				}
			});	
		
	});
	
	$("#saveType").click(function() {
		
		//TODO: 저장할 때 선택된 열 수정 처리
		jQuery('#grid').jqGrid('saveRow',lastSelType,false);  //마지막 셀 저장
		
		var curSelRow = $("#grid").jqGrid("getGridParam","selrow");
		$("#grid").jqGrid("saveRow",curSelRow); // 현재 셀 저장
		var curSelData = $("#grid").jqGrid("getRowData",curSelRow);
		
		for (var i = 0; i < arrType.length; i++) {
				if( arrType[i].CID == curSelRow ){
					if( !compareCurToLastDataType(curSelData, arrType[i]) ){
						if( arrType[i].CRUD == "R" || arrType[i].CRUD == "U"){
							arrType[i].CRUD = "U";
							$("#grid").jqGrid("setCell",curSelRow,"CRUD","U");
						}
						 
					}
				}
		}
				
		saveDataType();
		
		arrayView(arrType,"test1");
		arrayView(arrDetail,"test2");
		
		$.ajax({
			url: "exeSaveType.do",
			dataType : "json",
			type: "post",
			contentType: "application/json",
			data: JSON.stringify(arrType),
			success: function(data) {
				if (data.errMsg != null ) {
					alert(data.errMsg);
					
					/*setEditable("grid", "codeType",detectErrRow("grid") );
					$("#grid").jqGrid("editRow",detectErrRow("grid"));
					resetEditable("grid", "codeType");*/
					
				}else{
					clearDataSetType();
					
				}
				
				return true;
			}
		});
				
		arrayView(arrType,"test1");
		arrayView(arrDetail,"test2");
	});
	
$("#saveDetail").click(function() {
		
		//TODO: 저장할 때 선택된 열 수정 처리
		jQuery('#grid2').jqGrid('saveRow',lastSelDetail,false);  //마지막 셀 저장
		
		var curSelRow = $("#grid2").jqGrid("getGridParam","selrow");
		$("#grid2").jqGrid("saveRow",curSelRow); // 현재 셀 저장
		var curSelData = $("#grid2").jqGrid("getRowData",curSelRow);
		
		for (var i = 0; i < arrDetail.length; i++) {
				if( arrDetail[i].CID == curSelRow ){
					if( !compareCurToLastDataDetail(curSelData, arrDetail[i]) ){
						if( arrDetail[i].CRUD == "R" || arrDetail[i].CRUD == "U"){
							arrDetail[i].CRUD = "U";
							$("#grid2").jqGrid("setCell",curSelRow,"CRUD","U");
						}
						 
					}
				}
		}
				
		saveDataDetail();
				
		$.ajax({
			url: "exeSaveDetail.do",
			dataType : "json",
			type: "post",
			contentType: "application/json",
			data: JSON.stringify(arrDetail),
			success: function(data) {			
				if (data.errMsg != null ) {
					alert(data.errMsg);
				}else{
					clearDataSetDetail();
				}
				
				return true;
			}
		});
		
		arrayView(arrType,"test1");
		arrayView(arrDetail,"test2");
	});
	
	
	function saveDataType() {
		var dataArray = jQuery('#grid').jqGrid('getRowData');
		
		for (var i = 0; i < dataArray.length; i++) {
				var gridData = dataArray[i];
				
				if( gridData.CRUD == "C" ){
					for (var j = 0; j < arrType.length; j++) {
						var data = arrType[j];
						
						if( gridData.CID == data.CID ){
							
							arrType[j].codeType = gridData.codeType;
							arrType[j].codeDetail = gridData.codeType;
							arrType[j].codeName = gridData.codeName;
							//$("#grid").jqGrid("setCell",gridData.CID,"CID", gridData.codeType);
							//arrType[j].sortOrder = gridData.sortOrder;
							
						}
					}
					
				}else if( gridData.CRUD == "R" || gridData.CRUD == "U" ){
					for (var j = 0; j < arrType.length; j++) {
						var data = arrType[j];
						
						if( gridData.CID == data.CID ){
							arrType[j].codeType = gridData.codeType;
							arrType[j].codeName = gridData.codeName;
							//$("#grid").jqGrid("setCell",gridData.CID,"CID", gridData.codeType);
							//arrType[j].sortOrder = gridData.sortOrder;
						}
					}
					
				}	
			}
	}
	
	function saveDataDetail() {
		var dataArray = jQuery('#grid2').jqGrid('getRowData');
		
		for (var i = 0; i < dataArray.length; i++) {
			var gridData = dataArray[i];
			
			if( gridData.CRUD == "C" ){
				for (var j = 0; j < arrDetail.length; j++) {
					var data = arrDetail[j];
					
					if( gridData.CID == data.CID ){
						
						arrDetail[j].codeDetail = gridData.codeDetail;
						arrDetail[j].codeName = gridData.codeName;
						arrDetail[j].sortOrder = Number(gridData.sortOrder);
						//$("#grid2").jqGrid("setCell",gridData.CID,"CID", gridData.codeDetail);
						
					}
				}
				
			}else if( gridData.CRUD == "R" || gridData.CRUD == "U" ){
				for (var j = 0; j < arrDetail.length; j++) {
					var data = arrDetail[j];
					
					if( gridData.CID == data.CID ){
						arrDetail[j].codeDetail = gridData.codeDetail;
						arrDetail[j].codeName = gridData.codeName;
						arrDetail[j].sortOrder = Number(gridData.sortOrder);
						//$("#grid2").jqGrid("setCell",gridData.CID,"CID", gridData.codeDetail);
					}
				}
				
			}	
		}
	}
	
	function clearDataSetType() {
		var arrGridId = $("#grid").getDataIDs();
		cTypeId = 0;
		
		for (var i = 0; i < arrType.length; i++) {
			if( arrType[i].CRUD == "D" ){
				arrType = arrType.filter(function(data) {
					
					return data.CRUD != "D";
				});
			}
			
			arrType[i].CRUD = "R";
			
		}
		
		for (var i = 0; i < arrGridId.length; i++) {
			$("#grid").jqGrid("setCell",arrGridId[i],"CRUD","R");
		}
		
	}
	
	function clearDataSetDetail() {
		var arrGridId = $("#grid2").getDataIDs();
		cDetailId = 0;
		
		for (var i = 0; i < arrDetail.length; i++) {
			if( arrDetail[i].CRUD == "D" ){
				arrDetail = arrDetail.filter(function(data) {
					
					return data.CRUD != "D";
				});
			}
			
			arrDetail[i].CRUD = "R";
			
		}
		
		for (var i = 0; i < arrGridId.length; i++) {
			$("#grid2").jqGrid("setCell",arrGridId[i],"CRUD","R");
		}
		
	}
	
	function detectErrRow(grid) {
		var ids = $("#"+grid).getDataIDs();
		
		for (var i = 0; i < ids.length; i++) {
			var rowData = $("#"+grid).jqGrid("getRowData",ids[i]);
			
			for ( var prop in rowData) {
				if( rowData[prop] == "" ){
					
					return ids[i];
				}
			}
			
		}
	}
});